# -*- coding:utf-8 -*-
# TODO
# post cmt slow
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import json, time, sys, os, sets, logging
os.sys.path.append('../utils/constants/')
from constants import *
os.sys.path.append('../utils/memcacheDao/')
import memcacheDao
os.sys.path.append('../modules/antispam/')
import antispam
os.sys.path.append('../modules/comment/')
import commentLogic
os.sys.path.append('../modules/user/')
import userLogic
os.sys.path.append('../modules/jiong/')
import jiongLogic
os.sys.path.append('../modules/message/')
import messageLogic

from tornado.options import define, options
reload(sys)  
sys.setdefaultencoding("utf-8")  


class JiongHandler(tornado.web.RequestHandler):
    def get(self):
        mc = memcacheDao.memcacheDao()
        strType = self.get_argument('type')
        ret = {}
        #print strType
        if strType == 'list':
            # 获取列表(包括detail)
            timeline = self.get_argument('timeline', 'today')
            pageno   = int(self.get_argument('pageno', 0))
            if timeline not in sets.Set(['today', 'week', 'month', 'all',]):
                timeline = 'today'
            timeline = 'all'
            jiong_logic = jiongLogic.jiongLogic(self.application.db, mc.getInstance())
            ret = jiong_logic.trunc_by_time(timeline, pageno)
            logging.info('t:%s r:%u sort:%s p:%u' % (strType, ret['retcode'], timeline, pageno, ))
        elif strType == 'comment':
            jiong_id = int(self.get_argument('jiong_id'))
            pageno = int(self.get_argument('pageno', 0))
            jiong_logic = jiongLogic.jiongLogic(self.application.db, mc.getInstance())
            ret = jiong_logic.get_comment(jiong_id, pageno)
            logging.info('t:%s r:%u id:%u p:%u' % (strType, ret['retcode'], jiong_id, pageno, ))
        else:
            # 404
            ret['retcode'] = E_METHOD_NOT_EXIST
            ret['message'] = 'method not exists'
            logging.warning('t:%s method not exists' % (strType,))
        self.write(json.dumps(ret))

    def post(self):
        mc = memcacheDao.memcacheDao()
        strType = self.get_argument('type')
        argument_dict = {}
        ret = {}
        user_logic = userLogic.userLogic(self.application.db, mc.getInstance())
        string_base64 = self.get_argument('code', '')
        checkin_ret = user_logic.checkin(string_base64)
        if strType == 'post_jiong':
            if checkin_ret['retcode'] != 0:
                ret = checkin_ret
                logging.warning('t:%s chk:%u code:%s' % (strType, ret['retcode'], string_base64, ))
            else:
                anti = antispam.antispam(mc.getInstance())
                anti_item = {}
                anti_item['uip']     = self.request.remote_ip
                anti_item['content'] = self.get_argument('content')
                anti_item['user_id'] = checkin_ret['retbody']['user_id']
                anti_ret = anti.check_repeat(anti_item)
                if anti_ret['retcode'] != 0:
                    ret = anti_ret
                    logging.info('t:%s anti:%u' % (strType, ret['retcode'], ))
                else:
                    jiong_item = {}
                    #['title', 'content', 'uip', 'jiong_uid', 'jiong_uname', 'creat_time', 'last_reply_time',]
                    jiong_item['content']         = self.get_argument('content').encode('utf8')
                    jiong_item['uip']             = self.request.remote_ip
                    #jiong_item['tags']            = self.get_argument('tags', '').encode('utf8').split(' ')
                    jiong_item['jiong_uid']       = int(checkin_ret['retbody']['user_id'])
                    jiong_item['jiong_uname']     = checkin_ret['retbody']['user_name']
                    jiong_item['creat_time']      = int(time.time())
                    jiong_logic = jiongLogic.jiongLogic(self.application.db, mc.getInstance())
                    ret = jiong_logic.add(jiong_item)
                    logging.info('t:%s r:%u uid:%u un:%s ip:%s' % (strType, ret['retcode'], jiong_item['jiong_uid'], \
                            jiong_item['jiong_uname'], jiong_item['uip'],))
                    if 0 == ret['retcode']:
                        anti.set_content(anti_item)
                        # 给用户加活跃值
                        user_logic.bonus4post_jiong(checkin_ret['retbody']['user_id'])
                    #print ret
        elif strType == 'like_jiong':
            #argument_dict = self.get_checkin_argument()
            jiong_logic = jiongLogic.jiongLogic(self.application.db, mc.getInstance())
            like_item = {}
            like_item['like'] = 1
            like_item['uip'] = self.request.remote_ip
            like_item['jiong_id'] = int(self.get_argument('id'))
            ret = jiong_logic.like(like_item)
            # 给用户加活跃值
            if ret['retcode'] == 0 and checkin_ret['retcode'] == 0:
                user_logic.bonus4ding(int(checkin_ret['retbody']['user_id']))
                #print 'uid: %u like-bonus' % (int(checkin_ret['retbody']['user_id']),)
                # TODO 是否需要发送消息??
            logging.info('t:%s r:%u id:%u ip:%s' % (strType, ret['retcode'], like_item['jiong_id'], like_item['uip'],))
        elif strType == 'hate_jiong':
            #argument_dict = self.get_checkin_argument()
            jiong_logic = jiongLogic.jiongLogic(self.application.db, mc.getInstance())
            hate_item = {}
            hate_item['hate'] = 1
            hate_item['uip'] = self.request.remote_ip
            hate_item['jiong_id'] = int(self.get_argument('id'))
            ret = jiong_logic.hate(hate_item)
            # 给用户加活跃值
            if ret['retcode'] == 0 and checkin_ret['retcode'] == 0:
                user_logic.bonus4ding(int(checkin_ret['retbody']['user_id']))
                #print 'uid: %u hate-bonus' % (int(checkin_ret['retbody']['user_id']),)
            logging.info('t:%s r:%u id:%u ip:%s' % (strType, ret['retcode'], hate_item['jiong_id'], hate_item['uip'],))
        elif strType == 'ding_cmt':
            #argument_dict = self.get_register_argument()
            jiong_logic = jiongLogic.jiongLogic(self.application.db, mc.getInstance())
            ding_item = {}
            ding_item['uip']        = self.request.remote_ip
            ding_item['thread_id']  = int(self.get_argument('id'))
            ding_item['comment_id'] = int(self.get_argument('cmt_id'))
            ret = jiong_logic.ding_comment(ding_item)
            # 给用户加活跃值
            comment_uid    = int(self.get_argument('cmt_uid'))
            logmsg = 't:%s r:%u id:%u cid:%u cuid:%u ip:%s' % (strType, ret['retcode'], ding_item['thread_id'],\
                    ding_item['comment_id'], comment_uid,  ding_item['uip'],)
            if ret['retcode'] == 0 and checkin_ret['retcode'] == 0:
                user_logic.bonus4ding(int(checkin_ret['retbody']['user_id']))
                # 发信通知
                message_item = {}
                message_item['recv_uid']   = comment_uid
                message_item['send_uid']   = checkin_ret['retbody']['user_id']
                message_item['send_uname'] = checkin_ret['retbody']['user_name']
                message_item['itype']      = T_JIONG_COMMENT_DING
                message_item['creat_time'] = int(time.time())
                # $send_uname 顶了你的评论 $comment_content

                content = {}
                content['cmt'] = self.get_argument('cmt')
                content['id']  = ding_item['thread_id']
                content['sex'] = checkin_ret['retbody']['sex']
                message_item['content']    = json.dumps(content)
                message_logic = messageLogic.messageLogic(self.application.db)
                mret = message_logic.send(message_item)
                logmsg += ' msg:%u ruid:%u suid:%u itype:%u' % (mret['retcode'], message_item['recv_uid'], \
                        message_item['send_uid'], message_item['itype'],)
                #print message_logic.send(message_item)
            # 给被顶用户加声望值
            user_logic.bonus4dinged(comment_uid)
            logging.info(logmsg)
        elif strType == 'post_cmt':
            t = time.time()
            #argument_dict = self.get_register_argument()
            #string_base64 = self.get_argument('code')
            #print string_base64
            if checkin_ret['retcode'] != 0:
                ret = checkin_ret
                logging.warning('t:%s chk:%u code:%s' % (strType, ret['retcode'], string_base64, ))
            else:
                anti = antispam.antispam(mc.getInstance())
                anti_item = {}
                anti_item['uip']     = self.request.remote_ip
                anti_item['content'] = self.get_argument('reply')
                anti_item['user_id'] = checkin_ret['retbody']['user_id']
                anti_ret = anti.check_repeat(anti_item)
                if anti_ret['retcode'] != 0:
                    ret = anti_ret
                    logging.info('t:%s anti:%u' % (strType, ret['retcode'], ))
                else:
                    #print 'checkin - %.6f' % (time.time() - t)
                    t = time.time()
                    cmt_item = {}
                    # comment中content的格式
                    # 'reply'         -> 回复的内容
                    # 'quote_content' -> 被引用的内容
                    # 'quote_uid'     -> 被引用的用户id
                    # 'quote_uname'   -> 被引用的用户名
                    content = {}
                    content['reply']     = self.get_argument('reply')
                    content['cmt']       = self.get_argument('cmt', '')
                    content['cmt_id']    = int(self.get_argument('cmt_id', 0))
                    content['cmt_uid']   = int(self.get_argument('cmt_uid', 0))
                    content['cmt_uname'] = self.get_argument('cmt_uname', '')
                    jiong_id             = int(self.get_argument('id'))
                    jiong_uid            = int(self.get_argument('uid'))
                    rplmsg = ''
                    if content['cmt'] == '' or  0 == content['cmt_uid'] or '' == content['cmt_uname']:
                        del content['cmt']
                        del content['cmt_id']
                        del content['cmt_uid']
                        del content['cmt_uname']
                    else:
                        # 发信通知被回复人
                        # $send_uname 对你在 $thread_id 中的评论: $quote_content 进行了回复: $reply
                        message_item = {}
                        message_item['recv_uid']   = content['cmt_uid']
                        message_item['send_uid']   = checkin_ret['retbody']['user_id']
                        message_item['send_uname'] = checkin_ret['retbody']['user_name']
                        message_item['itype']      = T_JIONG_COMMENT_REPLY
                        message_item['creat_time'] = int(time.time())

                        content['id']  = jiong_id
                        content['sex'] = checkin_ret['retbody']['sex']
                        message_item['content']       = json.dumps(content)
                        message_logic = messageLogic.messageLogic(self.application.db)
                        mret = message_logic.send(message_item)
                        rplmsg = 'msg:%u ruid:%u suid:%u itype:%u' % (mret['retcode'], message_item['recv_uid'], \
                                message_item['send_uid'], message_item['itype'],)
                        #print message_logic.send(message_item)
                        #print 'message send 1 - %.6f' % (time.time() - t)
                        #t = time.time()
                    #['thread_id', 'comment_uid', 'comment_uname', 'creat_time', 'uip', 'content',]
                    cmt_item['content']       = content 
                    cmt_item['creat_time']    = int(time.time())
                    cmt_item['uip']           = self.request.remote_ip
                    cmt_item['age']           = int(time.strftime("%Y")) - checkin_ret['retbody']['birth_year']
                    cmt_item['sex']           = checkin_ret['retbody']['sex']
                    cmt_item['phone_type']    = self.get_argument('phone_type')
                    cmt_item['thread_id']     = int(self.get_argument('id'))
                    cmt_item['comment_uid']   = checkin_ret['retbody']['user_id']
                    cmt_item['comment_uname'] = checkin_ret['retbody']['user_name']
                    jiong_logic = jiongLogic.jiongLogic(self.application.db, mc.getInstance())
                    ret = jiong_logic.add_comment(cmt_item)
                    logmsg = 't:%s r:%u id:%u cuid:%u cun:%s ip:%s' % (strType, ret['retcode'], cmt_item['thread_id'],\
                            cmt_item['comment_uid'], cmt_item['comment_uname'], cmt_item['uip'],)
                    #print ret
                    if 0 == ret['retcode']:
                        anti.set_content(anti_item)
                        # 给用户加活跃值
                        user_logic.bonus4post_comment(checkin_ret['retbody']['user_id'])
                    #print 'post comment - %.6f' % (time.time() - t)
                    #t = time.time()
                    if content.has_key('cmt_uid') and jiong_uid != content['cmt_uid']:
                        # 如果回复楼主的评论(jiong_uid == cmt_uid)就不发了，否则会收到一个评论+回复的消息，都是重复的内容
                        # 发信通知jiong事发表者
                        # $send_uname 对你在 $thread_id 中的评论: $quote_content 进行了回复: $reply
                        message_item = {}
                        message_item['recv_uid']   = jiong_uid
                        message_item['send_uid']   = checkin_ret['retbody']['user_id']
                        message_item['send_uname'] = checkin_ret['retbody']['user_name']
                        message_item['itype']      = T_JIONG_COMMENT
                        message_item['creat_time'] = int(time.time())
                        message_item['content']    = json.dumps(content)
                        message_logic = messageLogic.messageLogic(self.application.db)
                        mret = message_logic.send(message_item)
                        logmsg += ' msg:%u ruid:%u suid:%u itype:%u' % (mret['retcode'], message_item['recv_uid'], \
                                message_item['send_uid'], message_item['itype'],)
                        #print 'message send 2 - %.6f' % (time.time() - t)
                        #t = time.time()
                        #print message_logic.send(message_item)
                    logging.info(logmsg)
        else:
            # 404
            ret['retcode'] = E_METHOD_NOT_EXIST
            ret['message'] = 'method not exists'
            logging.warning('t:%s method not exists' % (strType,))
        #print ret
        self.write(json.dumps(ret))
